package com.technology.education.ui.student.order

import android.content.Intent
import android.os.Handler
import android.view.Gravity
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.os.bundleOf
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope
import cn.jzvd.JzvdStd
import com.angcyo.dsladapter.*
import com.google.android.material.imageview.ShapeableImageView
import com.technology.education.R
import com.technology.education.base.BaseRecyclerTopBarFragment
import com.technology.education.data.SpKeys
import com.technology.education.data.model.TeacherOrderDetailModel
import com.technology.education.dslitem.ItemColumnTitleText
import com.technology.education.dslitem.ItemSingleButton
import com.technology.education.dslitem.ItemSingleImage
import com.technology.education.dslitem.ItemSingleText
import com.technology.education.dslitem.module.ItemOrderStatusCountdown
import com.technology.education.ext.*
import com.technology.education.ui.common.board_video.BoardVideoActivity
import com.technology.education.ui.common.video_play.VideoPlayActivity
import com.technology.education.utils.rom.*
import com.technology.education.utils.rom.MeizuUtils.commonROMPermissionApplyInternal
import com.technology.education.widget.CommonButton
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.util.startActivity
import java.util.*
import kotlin.collections.ArrayList

/**
 *@author:create by BZY
 *Date: 2022/3/8 08
 */
class OrderDetailFragment : BaseRecyclerTopBarFragment<OrderDetailViewModel>() {
    override fun initViews() {
        setTitle("订单详情")
        mViewModel.orderId = arguments?.getString("id") ?: ""
        initGrid(4)
        recycler.setBackgroundColor(getColor(R.color.white))
        enableSwipe()
    }

    override fun lazyLoadData() {
        loading()
    }

    private fun setUI(data: TeacherOrderDetailModel) {
        renderAdapter {
            clearAllItems()
            dslItem(ItemSingleText(data.teacherStatusInfo, itemSpan = -1)) {
                style.itemSpan = -1
                style.titleTextSize = 18f
                style.isBold = true
                style.bottomPadding = 2
                style.lineHeight = 0
                style.titleTextColor = R.color.theme_color
                itemPaddingTop = 20 * dpi
            }
            if (data.teachOrderState == "5") {
                dslItem(ItemSingleText("辅导已完成，请您对老师的辅导进行评价")) {
                    style.topPadding = 6
                    style.titleTextColor = R.color.text_m
                    style.titleTextSize = 14f
                    style.bottomPadding = 0
                    style.lineHeight = 0
                }
                dslItem(ItemSingleButton("立即评价")) {
                    style.parentGravity = Gravity.RIGHT
                    itemBindOverride = { itemHolder, _, _, _ ->
                        itemHolder.v<CommonButton>(R.id.button)?.apply {
                            updateLayoutParams {
                                width = 102 * dpi
                                height = 30 * dpi
                                textSize = 16f
                            }
                        }
                        itemHolder.v<LinearLayout>(R.id.ll_parent)?.apply {
                            gravity = Gravity.RIGHT
                            setPadding(0, 16 * dpi, 16 * dpi, 0)
                        }
                        itemClick = { view ->
                            navigation(
                                view, R.id.action_orderDetailFragment_to_evaluateFragment,
                                bundleOf("id" to mViewModel.orderId)
                            )
                        }
                    }
                }
            }

            if (data.teachOrderState == "2") {
                ///自动匹配,则展示正计时
                dslItem(
                    ItemOrderStatusCountdown(
                        formatTime(data.timeDiff),
                        "countdown", title = "等待老师接单中"
                    )
                ) {
                    itemTag = "countdown"
                    itemSpanCount = -1
                }
                startCountDown(data.timeDiff * 1000, 1)
            }
            if (data.teachOrderState == "1") {
                ///手动选择老师,则展示倒计时
                dslItem(
                    ItemOrderStatusCountdown(
                        formatTime(data.remainDuration / 1000),
                        "countdown"
                    )
                ) {
                    itemTag = "countdown"
                    itemSpanCount = -1
                    itemBindOverride = { itemHolder, _, _, payloads ->
                        itemHolder.tv(R.id.tv_status)?.apply {
                            setTextColor(getColor(R.color.red))
                            text =
                                "${
                                    if (payloads.isEmpty())
                                        formatTime(
                                            data.remainDuration / 1000
                                        )
                                    else payloads[0].toString()
                                }后老师没有接单,将会安排其他老师为您解答"
                        }
                    }
                }
                startCountDown(data.remainDuration, -1)
            }

            dslItem(ItemSingleText("辅导老师", itemSpan = -1)) {
                style.isBold = true
                style.topPadding = 20
            }
            data.teacher?.let {
                dslItem(R.layout.item_order_teacher_info) {
                    itemSpanCount = -1
                    itemBindOverride = { itemHolder, _, _, payload ->
                        itemTag = "teacher"
                        itemHolder.tv(R.id.tv_name)?.text = it.name
                        itemHolder.tv(R.id.tv_status)?.text = data.appointTeacherStatus
                        itemHolder.v<ImageView>(R.id.iv_like)?.apply {
                            setBackgroundResource(if (it.collected == "1") R.drawable.ic_baseline_favorite_24 else R.drawable.ic_baseline_favorite_border_24)
                        }
                        itemHolder.v<ShapeableImageView>(R.id.iv_header)?.apply {
                            header(it.avatar, this)
                        }
                        itemHolder.click(R.id.iv_like) { _ ->
                            mViewModel.collectTeacher(
                                it.id, if (it.isCollected) {
                                    it.collected = "0"
                                    "0"
                                } else {
                                    it.collected = "1"
                                    "1"
                                }
                            )
                            updateAdapterItem()
                        }
                    }
                }
            } ?: dslItem(R.layout.item_order_no_teacher) {
                itemSpanCount = -1
            }


            dslItem(R.layout.item_publish_order_flow) {
                itemSpanCount = -1
            }
            if (!data.questionImages.isNullOrEmpty()) {
                dslItem(ItemSingleText("问题图片", itemSpan = -1)) {
                    itemSpanCount = -1
                    style.isBold = true
                    style.lineHeight = 0
                }
                data.questionImages.forEachIndexed { index, s ->
                    dslItem(ItemSingleImage(s, getScreenWide() / 4 - 24 * dpi)) {
                        itemSpanCount = 1
                        itemClick = {
                            toPreviewPhoto(index, data.questionImages as ArrayList<String>)
                        }
                    }
                }
            }

            data.question?.let {
                //问题描述
                dslItem(ItemSingleText("问题描述", itemSpan = -1)) {
                    itemSpanCount = -1
                    style.lineHeight = 0
                    style.bottomPadding = 10
                    style.isBold = true
                }
                dslItem(ItemSingleText(it)) {
                    itemLeftInsert = 12 * dpi
                    itemRightInsert = 12 * dpi
                    style.lineColor = R.color.white
                    style.topPadding = 10
                    style.bottomPadding = 10
                    style.leftPadding = 12
                    style.rightPadding = 12
                    style.itemBackDrawable = R.drawable.round_gray
                    style.itemBackColor = 0
                    style.lineHeight = 0
                }
            }

            data.answer?.let {
                //辅导笔记展示
                dslItem(ItemSingleText("辅导笔记", itemSpan = -1)) {
                    itemSpanCount = -1
                    style.lineHeight = 0
                    style.bottomPadding = 0
                    style.isBold = true
                }
                dslItem(ItemSingleText(it)) {
                    itemLeftInsert = 12 * dpi
                    itemRightInsert = 12 * dpi
                    style.lineColor = R.color.white
                    style.topPadding = 10
                    style.bottomPadding = 10
                    style.leftPadding = 12
                    style.rightPadding = 12
                    style.itemBackDrawable = R.drawable.round_gray
                    style.itemBackColor = 0
                    style.lineHeight = 0
                }
            }
            if (!data.answerImages.isNullOrEmpty()) {
                data.answerImages.forEach {
                    dslItem(ItemSingleImage(it)) {
                        itemSpanCount = 1
                    }
                }
            }
            data.videoUrl?.let { url ->
                dslItem(ItemColumnTitleText("辅导视频", content = "(30天内可以回看)")) {
                    itemSpanCount = -1
                    style.contentTextSize = 12f
                    style.lineHeight = 0
                    style.bottomPadding = 0
                    style.contentTextColor = R.color.text_m
                    style.contentGravity = Gravity.BOTTOM or Gravity.LEFT
                    style.isBold = true
                }
                dslItem(R.layout.item_order_video) {
                    itemBindOverride = { itemHolder, _, _, _ ->
                        itemSpanCount = -1
                        itemHolder.v<ImageView>(R.id.video)?.apply {
                            loadImageVideo(url, this)
                        }
                        itemHolder.click(R.id.iv_play) {
                            startActivity(
                                VideoPlayActivity::class, Pair("url", url),
                                Pair("title", "辅导回看"), Pair("answer", data.answer ?: ""),
                                Pair(
                                    "image",
                                    (data.answerImages
                                        ?: arrayListOf()) as java.util.ArrayList<String>
                                )
                            )
                        }
                    }
                }
            }

            dslItem(ItemSingleText("订单信息", itemSpan = -1)) {
                itemSpanCount = -1
                style.isBold = true
            }

            dslItem(ItemColumnTitleText("订单编号", content = data.id)) {
                style.titleTextColor = R.color.text_m
                style.contentTextColor = R.color.text_m
                style.contentGravity = Gravity.RIGHT
                style.lineHeight = 0
                style.topPadding = 0
                itemSpanCount = -1
            }
            dslItem(ItemColumnTitleText("订单时间", content = data.placeTime)) {
                style.titleTextColor = R.color.text_m
                style.contentTextColor = R.color.text_m
                style.contentGravity = Gravity.RIGHT
                style.lineHeight = 0
                style.topPadding = 0
                itemSpanCount = -1
            }
            data.takeTime?.let {
                dslItem(ItemColumnTitleText("接单时间", content = it)) {
                    style.titleTextColor = R.color.text_m
                    style.contentTextColor = R.color.text_m
                    style.contentGravity = Gravity.RIGHT
                    style.lineHeight = 0
                    style.topPadding = 0
                    itemSpanCount = -1
                }
            }
            data.startTime?.let {
                dslItem(ItemColumnTitleText("辅导开始时间", content = it)) {
                    style.titleTextColor = R.color.text_m
                    style.contentTextColor = R.color.text_m
                    style.contentGravity = Gravity.RIGHT
                    style.lineHeight = 0
                    style.topPadding = 0
                    itemSpanCount = -1
                }
            }
            data.endTime?.let {
                dslItem(ItemColumnTitleText("辅导结束时间", content = it)) {
                    style.titleTextColor = R.color.text_m
                    style.contentTextColor = R.color.text_m
                    style.contentGravity = Gravity.RIGHT
                    style.lineHeight = 0
                    style.topPadding = 0
                    itemSpanCount = -1
                }
                dslItem(ItemColumnTitleText("辅导总时长", content = data.durationStr)) {
                    style.titleTextColor = R.color.text_m
                    style.contentTextColor = R.color.text_m
                    style.contentGravity = Gravity.RIGHT
                    style.lineHeight = 0
                    style.topPadding = 0
                    itemSpanCount = -1
                }
            }
        }
//        if (data.teachOrderState=="4"){
//            setBottomButton("进入辅导房间") {
//                val roomId = data.id.substring(10) as String
//                joinGroup(roomId) {
//                    startActivity(
//                        Intent(requireContext(), BoardVideoActivity::class.java).apply {
//                            putExtra("roomId", roomId)
//                            putExtra("orderId", data.id)
//                            putExtra("wait", false)
//                        }
//                    )
//                }
//            }
//        }
    }

    var timer: Timer? = null
    private fun startCountDown(timeDiff: Int, step: Int) {
        var time = timeDiff / 1000
        if (timer == null) {
            timer = Timer()
            timer!!.schedule(object : TimerTask() {
                override fun run() {
                    time += step
                    if (time < 0) {
                        timer!!.cancel()
                    }
                    myAdapter.findItemByTag("countdown")?.let {
                        myAdapter.notifyItemChanged(
                            it, formatTime(
                                time
                            )
                        )
                    }
                }

            }, 1000, 1000)
        }

    }

    override fun createObserver() {
        mViewModel.result.observe(this) {
            parseState(it, onSuccess = { data ->
                timer?.cancel()
                timer = null
                loadFinish()
                setUI(data)
                if (data.teachOrderState == "3" || data.teachOrderState == "4") {
                    showAlertPermission()
                }
            })
        }

        observe(SpKeys.REFRESH_ORDER_DETAIL, Boolean::class.java) {
            if (it) {
                refreshData()
            }
        }
        observe(SpKeys.CHANGE_ORDER_STATUS_WAIT_EVALUATE, String::class.java) {
            if (it == mViewModel.orderId) {
                refreshData()
                navigation(
                    requireView(), R.id.action_orderDetailFragment_to_evaluateFragment,
                    bundleOf("id" to mViewModel.orderId)
                )
            }
        }
    }

    private fun showAlertPermission() {
        if (!checkAlertPermission()) {

            notifyDialog(notify = "为了更好的进行视频辅导,请开启悬浮窗权限", confirm = {
                SettingsCompat.manageDrawOverlays(requireContext())
//                when {

//                    RomUtils.checkIsMiuiRom() -> {
//                        MiuiUtils.applyMiuiPermission(context)
//                    }
//                    RomUtils.checkIsMeizuRom() -> {
//                        MeizuUtils.applyPermission(context)
//                    }
//                    RomUtils.checkIsHuaweiRom() -> {
//                        HuaweiUtils.applyPermission(context)
//                    }
//                    RomUtils.checkIs360Rom() -> {
//                        QikuUtils.applyPermission(context)
//                    }
//                    RomUtils.checkIsOppoRom() -> {
//                        OppoUtils.applyOppoPermission(context)
//                    }
//                    else -> {
//                        commonROMPermissionApplyInternal(requireContext())
//                    }
//                }
            }, cancel = {
                toast("稍后可以在设置->应用->权限管理中开启悬浮窗权限")
            })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        timer?.cancel()
        timer = null
    }
}